/**
 * 测试人员任务管理路由
 *
 * Created by snowingsea on 2020/03/05.
 */
const middleware = require('./../middleware');
const tasks = require('./../../models/tasks');
const PhoenixError = require('./../../models/phoenix-error');
const files = require('../../models/files');

/**
 * 获取任务信息
 * @param req
 * @param res
 * @param next
 */
function getTask(req, res, next) { // eslint-disable-line no-unused-vars
  (async () => {
    const { fileIds } = req.$task;
    const filesArr = await files.getFilesByIds(fileIds, {
      projection: {
        fileId: '$_id',
        fileName: 1,
        _id: 0,
      },
    });
    res.json(Object.assign(tasks.getJson(req.$task), { files: filesArr }));
  })()
    .catch((err) => next(new PhoenixError(err)));
}

/**
 * 批量获取用户任务列表
 * @param req
 * @param res
 * @param next
 */
function getMyTasks(req, res, next) {
  const resTasks = {
    pagination: req.filter,
  };
  const options = tasks.getTaskOptions(req.query);
  options.creatorId = req.$token.userId;
  tasks.filter(req.filter, options)
    .then((data) => {
      resTasks.tasks = data.map((task) => tasks.getJson(task));
      return tasks.getCount(options);
    })
    .then((count) => {
      resTasks.pagination.total = count;
      res.json(resTasks);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 批量获取某个项目版本的任务列表
 * @param req
 * @param res
 * @param next
 */
function getTasksOfVersion(req, res, next) {
  const resTasks = {
    pagination: req.filter,
  };
  const options = tasks.getTaskOptions(req.query);
  options.versionId = req.$projectVersion._id; // eslint-disable-line no-underscore-dangle
  tasks.filter(req.filter, options)
    .then((data) => {
      resTasks.tasks = data.map((task) => tasks.getJson(task));
      return tasks.getCount(options);
    })
    .then((count) => {
      resTasks.pagination.total = count;
      res.json(resTasks);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 编辑任务
 * @param req
 * @param res
 * @param next
 */
function updateTask(req, res, next) {
  const { taskId } = req.params;
  tasks.updateTask(taskId, req.query)
    .then(() => tasks.getTask(taskId))
    .then((task) => {
      res.json(tasks.getJson(task));
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 批量编辑任务
 * @param req
 * @param res
 * @param next
 */
function updateMyTasks(req, res, next) {
  tasks.updateTasks(req.$token.userId, req.query)
    .then(() => {
      res.status(202).json();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = (app, prefix) => {
  const taskURL = `${prefix}/tasks/:taskId.json`;
  const tasksURL = `${prefix}/tasks.json`;
  const versionTasksURL = `${prefix}/project-versions/:projectVersionId/tasks.json`;

  // 获取任务
  app.get(taskURL, middleware.user.requireTokenUnexpired);
  app.get(taskURL, middleware.user.requireAvailable);
  app.get(taskURL, middleware.user.requireTester);
  app.get(taskURL, middleware.task.requireTaskExist);
  app.get(taskURL, middleware.task.requireTaskAccess);
  app.get(taskURL, getTask);

  // 获取用户任务列表
  app.get(tasksURL, middleware.user.requireTokenUnexpired);
  app.get(tasksURL, middleware.user.requireAvailable);
  app.get(tasksURL, middleware.user.requireTester);
  app.get(tasksURL, middleware.splitFilter);
  app.get(tasksURL, getMyTasks);

  // 获取项目版本的任务列表
  app.get(versionTasksURL, middleware.user.requireTokenUnexpired);
  app.get(versionTasksURL, middleware.user.requireAvailable);
  app.get(versionTasksURL, middleware.user.requireTester);
  app.get(versionTasksURL, middleware.projectVersion.requireProjectVersionExist);
  app.get(versionTasksURL, middleware.project.requireProjectAccess);
  app.get(versionTasksURL, middleware.projectVersion.requireProjectVersionAvailable);
  app.get(versionTasksURL, middleware.project.requireProjectAvailable);
  app.get(versionTasksURL, middleware.splitFilter);
  app.get(versionTasksURL, getTasksOfVersion);

  // 编辑任务
  app.put(taskURL, middleware.user.requireTokenUnexpired);
  app.put(taskURL, middleware.user.requireAvailable);
  app.put(taskURL, middleware.user.requireTester);
  app.put(taskURL, middleware.task.requireTaskExist);
  app.put(taskURL, middleware.task.requireTaskAccess);
  app.put(taskURL, updateTask);

  // 批量编辑用户任务列表
  app.put(tasksURL, middleware.user.requireTokenUnexpired);
  app.put(tasksURL, middleware.user.requireAvailable);
  app.put(tasksURL, middleware.user.requireTester);
  app.put(tasksURL, updateMyTasks);
};
